package com.seeyon.apps.taxFund.event;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.commonExt.util.CommonRestUtil;
import com.seeyon.apps.taxFund.api.ShuiJinEnum;
import com.seeyon.apps.util.CAP4FormKit;
import com.seeyon.apps.util.EnumUtilExt;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import com.seeyon.ctp.workflow.util.WorkflowEventConstants.WorkflowEventType;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

import java.util.*;

public class HLFaPiaoKaJuEvent extends AbstractWorkflowEvent {

    private static final Logger log = LoggerFactory.getLogger(HLFaPiaoKaJuEvent.class);

    private final CAP4FormManager cap4FormManager;

    private final EnumManager enumManager;

    public HLFaPiaoKaJuEvent(CAP4FormManager cap4FormManager, EnumManager enumManager) {
        this.cap4FormManager = cap4FormManager;
        this.enumManager = enumManager;
    }


    @Override
    public ApplicationCategoryEnum getAppName() {
        // TODO 自动生成的方法存根
        return ApplicationCategoryEnum.form;
    }

    @Override
    public WorkflowEventType getType() {
        // TODO 自动生成的方法存根
        return WorkflowEventType.Ext;
    }

    @Override
    public String getId() {
        return "hLFaPiaoKaJuEvent";
    }

    @Override
    public String getLabel() {
        return "发票开具申请";
    }

    /*
     * 流程发起前事件
     *
     */
    @Override
    public synchronized WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {
        log.info("=========================进入-红蓝发票开具申请=============================");
        WorkflowEventResult res = null;
        try {
            res = new WorkflowEventResult();
            Map<String, Object> map = data.getBusinessData();
            //获取表单的数据
            FormDataMasterBean master = (FormDataMasterBean) map.get("formDataBean");
            Long formId = master.getFormTable().getFormId();
            FormBean formBean = cap4FormManager.getForm(formId, true);

            Map<String, Object> apiParams = new HashMap<>();
            // 销方名称
            String xfmc = CAP4FormKit.getFieldValue(master, "销方名称", String.class, "0");
            apiParams.put("xfmc", xfmc);

            // 销方税号
            String xfsh = CAP4FormKit.getFieldValue(master, "销方税号", String.class, "0");
            apiParams.put("xfsh", xfsh);

            // 购方名称
            String gfmc = CAP4FormKit.getFieldValue(master, "购方名称", String.class, "0");
            apiParams.put("gfmc", gfmc);

            // 购方税号
            String gfsh = CAP4FormKit.getFieldValue(master, "购方税号", String.class, null);
            apiParams.put("gfsh", gfsh);
            // 发票种类 非必填
            Long fpzlId = CAP4FormKit.getFieldValue(master, "发票类型", Long.class, null);
            CtpEnumItem fpzlEnumItem = EnumUtilExt.getEnumItemByEnumItemId(fpzlId);
            if (fpzlEnumItem != null) {
                apiParams.put("fpzl", fpzlEnumItem.getValue());
            }else {
                log.error("发票种类获取失败");
            }
//            CtpEnumItem enumItemByEnumItemId = EnumUtilExt.getEnumItemByEnumItemId(fpzl);
            // 开票类型 非必填
            long kplxId = CAP4FormKit.getFieldValue(master, "开票类型", long.class, null);
            CtpEnumItem kplxEnumItem = EnumUtilExt.getEnumItemByEnumItemId(kplxId);
            if (kplxEnumItem != null) {
                apiParams.put("kplx", kplxEnumItem.getValue());
            }else {
                log.error("开票类型获取失败");
            }

            // 蓝票代码 蓝票为空,当充红已抵扣的专票时允许为空,其余情况均为必填项
            String lzfpdm = CAP4FormKit.getFieldValue(master, "蓝票代码", String.class, null);
            apiParams.put("lzfpdm", lzfpdm);

            // 蓝票号码 蓝票为空,当充红已抵扣的专票时允许为空,其余情况均为必填项
            String lzfphm = CAP4FormKit.getFieldValue(master, "蓝票号码", String.class, null);
            apiParams.put("lzfphm", lzfphm);

            // 清单标志  默认0
            String qdbz = "0";
            apiParams.put("qdbz", qdbz);
            // 合计金额(价税合计)
            Double hjje = CAP4FormKit.getFieldValue(master, "合计含税金额", Double.class, new Double(0));
            apiParams.put("jshj", hjje);
            // 合计不含税金额
            Double hjbhsje = CAP4FormKit.getFieldValue(master, "合计不含税金额", Double.class, new Double(0));
            apiParams.put("hjje", hjbhsje);
            // 合计税额
            Double hjse = CAP4FormKit.getFieldValue(master, "合计税额", Double.class, new Double(0));
            apiParams.put("hjse", hjse);

            // 单据日期
            Date djrq = CAP4FormKit.getFieldValue(master, "单据日期", Date.class, new Date());
            log.info("获取到单据日期:{}", djrq);
            apiParams.put("djrq", DateUtil.format(djrq, "yyyy-MM-dd HH:mm:ss"));
            // 业务来源
            apiParams.put("xtly", "JDXH");
            // 流水号
            String xsdjbh = CAP4FormKit.getFieldValue(master, "单据编号", String.class, "");
            apiParams.put("xsdjbh", xsdjbh);

            // ------ 明细 ---
            FormTableBean dtlTableBean = CAP4FormKit.getSubTableBeanByDisplay(formBean, "用途金额");
            Assert.notNull(dtlTableBean, "【{}】不存在", "用途金额");
            List<Map<String, Object>> listOrders = new ArrayList<>();
            for (FormDataSubBean subData : master.getSubData(dtlTableBean.getTableName())) {
                log.info("开始获取用途金额表数据");
                Map<String, Object> listOrder = new HashMap<>();
                // 商品名称
                listOrder.put("spmc", CAP4FormKit.getFieldValue(subData, "用途说明", String.class, "0"));

                // 金额
                listOrder.put("je", CAP4FormKit.getFieldValue(subData, "用途金额", Double.class, new Double(0)));
                // 发票行性质
                Long fphxzId = CAP4FormKit.getFieldValue(subData, "发票行性质", Long.class, null);
                CtpEnumItem fphxzEnumItem = EnumUtilExt.getEnumItemByEnumItemId(fphxzId);

                if (fphxzEnumItem != null) {
                    listOrder.put("fphxz", fphxzEnumItem.getValue());
                }else {
                    log.error("发票行性质获取失败");
                }
                // 含税标志
                Long hsbzId = CAP4FormKit.getFieldValue(subData, "含税标志", Long.class, 0L);
                CtpEnumItem hsbzEnumItem = EnumUtilExt.getEnumItemByEnumItemId(hsbzId);
                if (hsbzEnumItem != null) {
                    listOrder.put("hsjbz", hsbzEnumItem.getValue());
                }else {
                    listOrder.put("hsjbz", "0");
                }
                // 税率
                listOrder.put("slv", CAP4FormKit.getFieldValue(subData, "税率", String.class, "0"));
                // 税额
                listOrder.put("se", CAP4FormKit.getFieldValue(subData, "税额", Double.class, new Double(0)));
                //  税收分类编码
                listOrder.put("flbm", CAP4FormKit.getFieldValue(subData, "税收分类编码", String.class, "0"));
                //  优惠政策标志
                Long yhzcId = CAP4FormKit.getFieldValue(subData, "优惠政策标志", Long.class, 0L);
                CtpEnumItem enumItem = EnumUtilExt.getEnumItemByEnumItemId(yhzcId);
                if (enumItem != null) {
                    listOrder.put("yhbz", enumItem.getValue());
                }else {
                    listOrder.put("yhbz", "0");
                }
                log.info("获取用途金额表数据：{}", JSON.toJSONString(listOrder));
                listOrders.add(listOrder);
            }

            log.info("发票开具申请接口调用开始,请求参数：{}", JSON.toJSONString(apiParams));
            apiParams.put("listOrder", listOrders);
            ResponseEntity<String> resp = CommonRestUtil.post(ShuiJinEnum.ORDER_INFO, null, apiParams);
            String bodyStr = resp.getBody();
            JSONObject body = JSONObject.parseObject(bodyStr);
            String returnCode = body.getString("returnCode");
            if (!"1000".equals(returnCode)) {
                log.error("发票开具申请接口调用失败，返回信息：{}", body.getString("returnMsg"));
                res.setAlertMessage(StrUtil.format("【{}】异常【{}】", "发票开具申请", body.getString("returnMsg")));
            }

            log.info("发票开具申请接口调用完成");
        } catch (Exception e) {
            res.setAlertMessage(StrUtil.format("【{}】异常【{}】", "发票开具申请", e.getMessage()));
        }
        log.info("=========================退出-发票开具申请-onBeforeFinishWorkitem=============================");
        return res;
    }
}
